package com.imdroid.lite;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.acra.ACRA;
import org.acra.ErrorReporter;
import org.acra.ReportField;
import org.acra.ReportingInteractionMode;
import org.acra.annotation.ReportsCrashes;
import org.acra.collector.CrashReportData;
import org.acra.sender.ReportSender;
import org.acra.sender.ReportSenderException;
import org.apache.commons.net.ftp.FTPClient;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.Toast;

import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.MKGeneralListener;
import com.imdroid.lite.model.User;
import com.imdroid.lite.net.HttpHelper;

@ReportsCrashes(formKey = "dGVacG0ydVHnaNHjRjVTUTEtb3FPWGc6MQ", mode = ReportingInteractionMode.SILENT)
public class IMDroid extends Application {
	/**
	 * The instance of the application
	 */
	private static IMDroid instance;
	/**
	 * The current user
	 */
	private static User currentUser;
	/**
	 * Temp folder
	 */
	public static final String TEMP_FOLDER = Environment
			.getExternalStorageDirectory() + "/IMDroid/temp/";
	/**
	 * Temp folder
	 */
	public static final String TEMP_ERROR = Environment
			.getExternalStorageDirectory() + "/IMDroid/error/";

	/**
	 * the file of security file.
	 */
	public static String APP_FOLDER = Environment.getExternalStorageDirectory()
			.getPath() + "/IMDroid/newapp/";

	public BMapManager mBMapMan = null;

	static {
		// 创建程序所需目录
		File file = new File(TEMP_FOLDER);

		if (!file.exists())
			file.mkdirs();

		file = new File(APP_FOLDER);
		if (!file.exists())
			file.mkdirs();

		file = new File(TEMP_ERROR);
		if (!file.exists())
			file.mkdirs();
	}

	public IMDroid() {
		instance = this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Application#onCreate()
	 */
	public void onCreate() {
		super.onCreate();

		mBMapMan = new BMapManager(this);
		mBMapMan.init(getResources().getString(R.string.baidu_map_key),
				new MyGeneralListener());
		mBMapMan.getLocationManager().setNotifyInternal(4, 3);

		ACRA.init(this);
		ErrorReporter reporter = ACRA.getErrorReporter();
		reporter.removeAllReportSenders();
		reporter.addReportSender(new CrashReportSender());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.app.Application#onTerminate()
	 */
	public void onTerminate() {
		if (mBMapMan != null) {
			mBMapMan.destroy();
			mBMapMan = null;
		}
		super.onTerminate();
	}

	public static class MyGeneralListener implements MKGeneralListener {
		@Override
		public void onGetNetworkState(int iError) {
			Log.d("MyGeneralListener", "onGetNetworkState error is " + iError);
			Toast.makeText(getAppContext(), "Network is not availble",
					Toast.LENGTH_LONG).show();
		}

		@Override
		public void onGetPermissionState(int iError) {

		}
	}

	/**
	 * Get the application context
	 * 
	 * @return the application context
	 */
	public static IMDroid getAppContext() {
		return instance;
	}

	/**
	 * Get the user
	 * 
	 * @return the current user
	 */
	public static User getUser() {
		if (currentUser == null) {
			loadUser();
		}
		return currentUser;
	}

	/**
	 * Loca the user from sp
	 */
	private static void loadUser() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getAppContext());

		if (prefs == null || prefs.getInt("User_id", -1) <= 0) {
			currentUser = null;
			return;
		}

		currentUser = new User();
		// 用户ID
		currentUser.setUser_id(prefs.getInt("User_id", -1));
		// 用户名
		currentUser.setUser_name(prefs.getString("user_name", null));
		// 密码
		currentUser.setPassword(prefs.getString("password", null));
		// 电话号码
		currentUser.setMobile_phone(prefs.getString("mobile_number", null));
		// 车辆型号
		currentUser.setVechile_model(prefs.getString("vehicle", null));
		// 车牌
		currentUser.setBoard_plate(prefs.getString("Board_plate", null));
		// 昵称
		currentUser.setNickname(prefs.getString("Nickname", null));
		// 用户类型
		currentUser.setType(prefs.getInt("type", 3));
		// 车机ID
		currentUser.setParentId(prefs.getInt("parent_id", -1));
		// 车机ID
		currentUser.setParentName(prefs.getString("parent_name", null));
		// 车队进入密码
		currentUser.setTeam_access_code(prefs.getString("team_access_code",
				null));
	}

	/**
	 * Register the user
	 */
	public static void registerUser(User user) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getAppContext());
		Editor editor = prefs.edit();
		// 用户ID
		editor.putInt("User_id", user.getUser_id());
		// 用户名
		editor.putString("user_name", user.getUser_name());
		// 密码
		editor.putString("password", user.getPassword());
		// 电话号码
		editor.putString("mobile_number", user.getMobile_phone());
		// 车辆型号
		editor.putString("vehicle", user.getVechile_model());
		// 车牌
		editor.putString("Board_plate", user.getBoard_plate());
		// 用户类型
		editor.putString("Nickname", user.getNickname());
		// 用户类型
		editor.putInt("type", user.getType());
		// 车机ID
		editor.putInt("parent_id", user.getParentId());
		// 车机ID
		editor.putString	("parent_name", user.getParentName());

		// 车机ID
		editor.putString("team_access_code", user.getTeam_access_code());
		editor.commit();
		currentUser = user;
	}

	/**
	 * Clear all the data
	 */
	public static void clear() {
		currentUser = null;
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getAppContext());
		Editor editor = prefs.edit();
		editor.clear();
		editor.commit();
	}

	/**
	 * Get the version number of the application
	 * 
	 * @return the version number of the application
	 * @throws NameNotFoundException
	 */
	public static String getAppVersion() throws NameNotFoundException {
		// 版本名
		PackageManager manager = getAppContext().getPackageManager();
		PackageInfo info = manager.getPackageInfo(getAppContext()
				.getPackageName(), 0);
		return info.versionName;
	}

	/**
	 * Get the last contact sync date
	 * 
	 * @return the date of last contact last sync
	 */
	public static Date getContactLastSync() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getAppContext());
		long time = prefs.getLong("contactLastSync", 0);
		return new Date(time);

	}

	/**
	 * Set the last contact sync date
	 * 
	 * @param date
	 *            the date of the contact last sync
	 */
	public static void setContactLastSync(Date date) {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(IMDroid.getAppContext());
		Editor editor = prefs.edit();
		editor.putLong("contactLastSync", date.getTime());
		editor.commit();
	}

	/**
	 * The error report sender
	 * 
	 */
	@SuppressLint("SimpleDateFormat")
	public class CrashReportSender implements ReportSender {
		/*
		 * (non-Javadoc)
		 * 
		 * @see
		 * org.acra.sender.ReportSender#send(org.acra.collector.CrashReportData)
		 */
		public void send(CrashReportData arg0) throws ReportSenderException {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss");
			String errorFileName = sdf.format(new Date()) + ".txt";
			File file = new File(TEMP_ERROR + errorFileName);
			BufferedWriter output = null;
			try {
				// 创建文件
				if (!file.exists())
					file.createNewFile();

				output = new BufferedWriter(new FileWriter(file));
				// 写入日志内容
				output.write("[ANDROID_VERSION]:"
						+ arg0.getProperty(ReportField.ANDROID_VERSION) + "\n");
				output.write("[APP_VERSION_CODE]:"
						+ arg0.getProperty(ReportField.APP_VERSION_CODE) + "\n");
				output.write("[APP_VERSION_NAME]:"
						+ arg0.getProperty(ReportField.APP_VERSION_NAME) + "\n");
				output.write("[APPLICATION_LOG]:"
						+ arg0.getProperty(ReportField.APPLICATION_LOG) + "\n");
				output.write("[AVAILABLE_MEM_SIZE]:"
						+ arg0.getProperty(ReportField.AVAILABLE_MEM_SIZE)
						+ "\n");
				output.write("[BRAND]:" + arg0.getProperty(ReportField.BRAND)
						+ "\n");
				output.write("[BUILD]:" + arg0.getProperty(ReportField.BUILD)
						+ "\n");
				output.write("[CRASH_CONFIGURATION]:"
						+ arg0.getProperty(ReportField.CRASH_CONFIGURATION)
						+ "\n");
				output.write("[CUSTOM_DATA]:"
						+ arg0.getProperty(ReportField.CUSTOM_DATA) + "\n");
				output.write("[DEVICE_FEATURES]:"
						+ arg0.getProperty(ReportField.DEVICE_FEATURES) + "\n");
				output.write("[DEVICE_ID]:"
						+ arg0.getProperty(ReportField.DEVICE_ID) + "\n");
				output.write("[DISPLAY]:"
						+ arg0.getProperty(ReportField.DISPLAY) + "\n");
				output.write("[DROPBOX]:"
						+ arg0.getProperty(ReportField.DROPBOX) + "\n");
				output.write("[DUMPSYS_MEMINFO]:"
						+ arg0.getProperty(ReportField.DUMPSYS_MEMINFO) + "\n");
				output.write("[ENVIRONMENT]:"
						+ arg0.getProperty(ReportField.ENVIRONMENT) + "\n");
				output.write("[EVENTSLOG]:"
						+ arg0.getProperty(ReportField.EVENTSLOG) + "\n");
				output.write("[FILE_PATH]:"
						+ arg0.getProperty(ReportField.FILE_PATH) + "\n");
				output.write("[INITIAL_CONFIGURATION]:"
						+ arg0.getProperty(ReportField.INITIAL_CONFIGURATION)
						+ "\n");
				output.write("[INSTALLATION_ID]:"
						+ arg0.getProperty(ReportField.INSTALLATION_ID) + "\n");
				output.write("[IS_SILENT]:"
						+ arg0.getProperty(ReportField.IS_SILENT) + "\n");
				output.write("[LOGCAT]:" + arg0.getProperty(ReportField.LOGCAT)
						+ "\n");
				output.write("[MEDIA_CODEC_LIST]:"
						+ arg0.getProperty(ReportField.MEDIA_CODEC_LIST) + "\n");
				output.write("[PACKAGE_NAME]:"
						+ arg0.getProperty(ReportField.PACKAGE_NAME) + "\n");
				output.write("[PHONE_MODEL]:"
						+ arg0.getProperty(ReportField.PHONE_MODEL) + "\n");
				output.write("[PRODUCT]:"
						+ arg0.getProperty(ReportField.PRODUCT) + "\n");
				output.write("[RADIOLOG]:"
						+ arg0.getProperty(ReportField.RADIOLOG) + "\n");
				output.write("[REPORT_ID]:"
						+ arg0.getProperty(ReportField.REPORT_ID) + "\n");
				output.write("[SETTINGS_SECURE]:"
						+ arg0.getProperty(ReportField.SETTINGS_SECURE) + "\n");
				output.write("[SETTINGS_SYSTEM]:"
						+ arg0.getProperty(ReportField.SETTINGS_SYSTEM) + "\n");
				output.write("[SHARED_PREFERENCES]:"
						+ arg0.getProperty(ReportField.SHARED_PREFERENCES)
						+ "\n");
				output.write("[STACK_TRACE]:"
						+ arg0.getProperty(ReportField.STACK_TRACE) + "\n");
				output.write("[THREAD_DETAILS]:"
						+ arg0.getProperty(ReportField.THREAD_DETAILS) + "\n");
				output.write("[TOTAL_MEM_SIZE]:"
						+ arg0.getProperty(ReportField.TOTAL_MEM_SIZE) + "\n");
				output.flush();
				output.close();
			} catch (IOException e) {
				e.printStackTrace();
			} finally {

				try {
					if (output != null)
						output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			FTPClient ftpClient = new FTPClient();
			FileInputStream input = null;
			try {
				ftpClient.connect(HttpHelper.FTPAddress);
				ftpClient.login("error", "error");// 登录
				ftpClient.changeWorkingDirectory("/error");
				ftpClient.setBufferSize(1024);
				ftpClient.setControlEncoding("UTF-8");
				ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
				input = new FileInputStream(file);
				ftpClient.storeFile(errorFileName, input);
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					if (input != null)
						input.close();

					if (ftpClient != null && ftpClient.isConnected())
						ftpClient.disconnect();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
}
